//
//  JKSquareTableViewController.swift
//  afanti
//
//  Created by albert on 16/4/16.
//  Copyright © 2016年 albert. All rights reserved.
//

import UIKit

/** 答题广场tableView的cell重用ID */
private let reuseId = "square"

/** collectionView的cell ID */
private let collectionCellID = "cell"

/** collectionView的组标题 ID */
private let collectionViewSectionHeaderID = "CollectionHeader"

/** item间距 20 */
private let itemMargin: CGFloat = 20

/** 每行的item数量 4 */
private let itemCount: CGFloat = 4

/** item高度 25 */
private let itemHeight: CGFloat = 25

/** collectionView最大高度 265 */
private let collectionViewMaxHeight: CGFloat = 265

class JKSquareTableViewController: UITableViewController {
    
    var btn: UIButton?
    var _collectionView: UICollectionView?
    var _selectedRow = 0
    var _selectedTitleButtonGrade: UIButton?
    var _selectedTitleButtonSubject: UIButton?
    
    //MARK: - 懒加载 年级及对应的学科
    lazy var grades: [JKGradeItem] = {
        var grades: [JKGradeItem] = []
        
        /** 九年级学科 || 高中学科 || 所有学科 */
        let highSchoolSubjects = ["全部", "数学", "语文", "英语", "生物", "政治", "历史", "地理", "物理", "化学"]
        
        /** 全部 */
        let allItem = JKGradeItem.item("全部", subjects: highSchoolSubjects)
        grades.append(allItem)
        
        /** 小学 */
        let primaryItem = JKGradeItem.item("小学", subjects: ["全部", "数学", "语文", "英语"])
        grades.append(primaryItem)
        
        /** 七年级 */
        let grade7Item = JKGradeItem.item("七年级", subjects: ["全部", "数学", "语文", "英语", "生物", "政治", "历史", "地理"])
        grades.append(grade7Item)
        
        /** 八年级 */
        let grade8Item = JKGradeItem.item("八年级", subjects: ["全部", "数学", "语文", "英语", "生物", "政治", "历史", "地理", "物理"])
        grades.append(grade8Item)
        
        /** 九年级 */
        let grade9Item = JKGradeItem.item("九年级", subjects: highSchoolSubjects)
        grades.append(grade9Item)
        
        /** 高一 */
        let high1Item = JKGradeItem.item("高一", subjects: highSchoolSubjects)
        grades.append(high1Item)
        
        /** 高二 */
        let high2Item = JKGradeItem.item("高二", subjects: highSchoolSubjects)
        grades.append(high2Item)
        
        /** 高三 */
        let high3Item = JKGradeItem.item("高三", subjects: highSchoolSubjects)
        grades.append(high3Item)
        
        return grades
    }()
    
    //MARK: - 懒加载 初始化collectionView的容器view
    lazy var coverView: UIView = {
        let coverView = UIView(frame: CGRect(x: 0, y: 64, width: JKScreenW, height: JKScreenH - 64))
        
        coverView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
        
        return coverView
    }()
    
    //MARK: - 初始化flowLayout
    func setUpflowLayout() -> UICollectionViewFlowLayout{
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.headerReferenceSize = CGSize(width: view.width, height: itemHeight + 10)
        // 行间距
        flowLayout.minimumLineSpacing = itemMargin * 0.5
        
        let itemW = (view.width - (itemCount + 1) * itemMargin) / itemCount
        let itemH: CGFloat = itemHeight
        flowLayout.itemSize = CGSize(width: itemW, height: itemH)
        
        return flowLayout
    }
    
    //MARK: - 初始化collectionView
    func setUpCollectionView() -> UICollectionView{
        let flowLayout = setUpflowLayout()
        
        // collectionView后面的按钮，点击退出collectionView
        let button = UIButton(type: UIButtonType.Custom)
        button.x = 0
        button.y = 0
        button.width = view.width
        button.height = view.height
        button.addTarget(self, action: "coverViewBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        coverView.addSubview(button)
        
        // collectionView
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.width, height: collectionViewMaxHeight), collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.whiteColor()
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        // 注册cell和组标题
        collectionView.registerNib(UINib(nibName: "JKCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: collectionCellID)
        collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: collectionViewSectionHeaderID)
        
        // 默认选中第一个
        let indexPathGrade = NSIndexPath(forItem: 0, inSection: 0)
        collectionView.selectItemAtIndexPath(indexPathGrade, animated: false, scrollPosition: UICollectionViewScrollPosition.Top)
        
        _collectionView = collectionView;
        
        coverView.addSubview(collectionView)
        
        return collectionView;
    }
    
    /** 点击collectionView下面的按钮 */
    func coverViewBtnClick(){
        titleViewClick(btn!)
    }
    
    //MARK: - 初始化导航栏
    func setupNav(){
        let button = UIButton(type: UIButtonType.Custom)
        button.setTitle("全部", forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(17)
        button.addTarget(self, action: "titleViewClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.titleView = button
        btn = button
    }
    
    //MARK: - 初始化tableView
    func setupTableView(){
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.registerNib(UINib(nibName: "JKSquareCell", bundle: nil), forCellReuseIdentifier: reuseId)
    }
    
    //MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化导航栏
        setupNav()
        
        // 初始化tableView
        setupTableView()
        
        // 初始化collectionView
        setUpCollectionView()
    }
    
    //MARK: - 点击顶部标题
    func titleViewClick(button: UIButton){
        button.selected = !button.selected
        
        // 动画显示和隐藏
        if button.selected {
            coverView.alpha = 0
            UIApplication.sharedApplication().keyWindow!.addSubview(coverView)
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.coverView.alpha = 1
            })
            
        }else{
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.coverView.alpha = 0
                }, completion: { (Bool) -> Void in
                    self.coverView.removeFromSuperview()
            })
        }
        
    }
}

// MARK: - Table view data source
extension JKSquareTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseId)
        
        
        return cell!
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 180
    }
}

//MARK: - collectionView的代理和数据源
extension JKSquareTableViewController: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0{
            return grades.count
        }else {
            let indexPath = collectionView.indexPathsForSelectedItems()![0]
            let grade = grades[indexPath.row]
            return (grade.subjects?.count)!
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        if indexPath.section == 0{
            let cell: JKCollectionViewCell = (collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellID, forIndexPath: indexPath)) as! JKCollectionViewCell
            let item = grades[indexPath.row]
            cell.item = item
            
            // 默认选中第一个
            if indexPath.row == 0{
                _selectedTitleButtonGrade = cell.titleButton
                _selectedTitleButtonGrade?.selected = true
            }
            
            return cell
            
        }else{
            let cell: JKCollectionViewCell = (collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellID, forIndexPath: indexPath)) as! JKCollectionViewCell
            let item = grades[collectionView.indexPathsForSelectedItems()![0].row]
            cell.titleButton.setTitle(item.subjects![indexPath.row], forState: UIControlState.Normal)
            
            return cell
        }
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        
        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: collectionViewSectionHeaderID, forIndexPath: indexPath)
        headerView.backgroundColor = JKGlobalBackGroundColor
        
        let label = UILabel();
        label.frame = CGRect(x: 0, y: 0, width: JKScreenW, height: itemHeight + 10)
        label.textAlignment = NSTextAlignment.Center
        if indexPath.section == 0 {
            label.text = "年级"
        }else{
            label.text = "学科"
        }
        
        headerView.subviews.first?.removeFromSuperview()
        headerView.addSubview(label)
        
        return headerView
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.section == 0{
            let cell = collectionView.cellForItemAtIndexPath(indexPath) as! JKCollectionViewCell
            _selectedTitleButtonGrade?.selected = false
            _selectedTitleButtonSubject?.selected = false
            _selectedTitleButtonGrade = cell.titleButton
            _selectedTitleButtonGrade?.selected = true
            
            let indexSet = NSIndexSet(index: 1)
            collectionView.reloadSections(indexSet)
            _selectedRow = indexPath.row
            
            let item = grades[indexPath.row]

            /** 计算collectionView高度 */
            var collectionViewH: CGFloat = 0
            let count = CGFloat((item.subjects?.count)!)
            if count > itemCount * 2{
                collectionViewH = collectionViewMaxHeight
            }else if count > itemCount{
                collectionViewH = collectionViewMaxHeight - (itemMargin * 0.5 + itemHeight)
            }else{
                collectionViewH = collectionViewMaxHeight - (itemMargin * 0.5 + itemHeight) * 2
            }
            
            _collectionView?.frame = CGRect(x: 0, y: 0, width: view.width, height: collectionViewH)
            
        }else{
            
            let cell = collectionView.cellForItemAtIndexPath(indexPath) as! JKCollectionViewCell
            _selectedTitleButtonSubject?.selected = false
            _selectedTitleButtonSubject = cell.titleButton
            _selectedTitleButtonSubject?.selected = true
            
            let item = grades[_selectedRow]
            let subject = item.subjects![indexPath.row]
            if item.grade == "全部" {
                btn?.setTitle(subject, forState: UIControlState.Normal)
            }else if subject == "全部" {
                btn?.setTitle(item.grade, forState: UIControlState.Normal)
            }else{
                btn?.setTitle("\(item.grade!) \(item.subjects![indexPath.row])", forState: UIControlState.Normal)
            }
            btn?.sizeToFit()
            titleViewClick(btn!)
        }
    }
}

//MARK: - FlowLayout的代理
extension JKSquareTableViewController: UICollectionViewDelegateFlowLayout{
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
        return UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
    }
}